"""
网络：支付接口
"""

import json
from random import randint
from datetime import datetime

import qrcode
import requests

from src.config import settings
from src.models.user import User
from src.schemas.order import OrderCreate


def create_order(amount: float):
    """创建订单"""
    user = User.get_user(require_login=True)
    if not user:
        return 1001, '用户未登录！'
    order_no = datetime.now().strftime('%Y%m%d%H%M%S') + str(randint(1000, 10000))
    order_name = f'桌面客户端充值￥{amount}'
    try:
        order_obj = OrderCreate(
            order_no=order_no, order_name=order_name, order_amount=amount)
    except ValueError as e:
        err = eval(e.json())[0]['msg']
        return 1002, err
    try:
        response = requests.post(settings.alipay_order_create_url, data=order_obj.json(
        ), headers={'token': user.token})
    except Exception as e:
        return 1003, '网络请求出错!'
    res = response.json()
    if response.status_code == 200 and res['code'] == 2000:
        qrcode_url = res['data']['qrcode']
        img = qrcode.make(qrcode_url).get_image().resize((200, 200))
        return 1000, {'order_no': order_no, 'qrcode': img}
    else:
        return 1004, res['message']


def order_status(order_no: str):
    """查询订单"""
    user = User.get_user(require_login=True)
    if not user:
        return 1001, '用户未登录！'
    try:
        response = requests.post(settings.alipay_order_status_url, data=json.dumps(
            {'order_no': order_no}), headers={'token': user.token})
    except Exception as e:
        return 1002, '网络请求出错!'
    res = response.json()
    if response.status_code == 200 and res['code'] == 2000:
        return 1000, res['data']
    else:
        return 1003, res['message']


def cancel_order(order_no: str):
    """取消订单"""
    user = User.get_user(require_login=True)
    if not user:
        return 1001, '用户未登录！'
    try:
        response = requests.post(settings.alipay_order_cancel_url, data=json.dumps(
            {'order_no': order_no}), headers={'token': user.token})
    except Exception as e:
        return 1002, '网络请求出错!'
    res = response.json()
    if response.status_code == 200 and res['code'] == 2000:
        return 1000, res['message']
    else:
        return 1003, res['message']


if __name__ == '__main__':
    code, res = create_order(1.2)
    print(res)
    res2 = order_status(res['order_no'])
    print(res2)
    res3 = cancel_order(res['order_no'])
    print(res3)
